<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检索" prop="search">
        <el-input v-model="queryParams.search" placeholder="请输入检索信息" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="供应商" prop="providerId">
        <el-select v-model="queryParams.providerId" placeholder="请选择供应商">
          <el-option v-for="item in providerList" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择日期" prop="dateTime">
        <el-date-picker clearable v-model="queryParams.dateTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="业务类型" prop="businessId">
        <el-select v-model="queryParams.businessId" placeholder="请选择业务类型">
          <el-option label="生产入库" value="0"></el-option>
          <el-option label="采购入库" value="1"></el-option>
          <el-option label="退货入库" value="2"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="合同类型" prop="contractId">
        <el-select v-model="queryParams.contractId" placeholder="请选择合同类型">
          <el-option label="采购合同" value="0"></el-option>
          <el-option label="销售合同" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="申请状态" prop="createStatus">
        <el-select v-model="queryParams.createStatus" placeholder="请选择申请状态">
          <el-option label="待审核" value="0"></el-option>
          <el-option label="已审核" value="1"></el-option>
          <el-option label="未提交" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="updateStatus">
        <el-select v-model="queryParams.updateStatus" placeholder="请选择审核状态">
          <el-option label="驳回" value="0"></el-option>
          <el-option label="审核通过" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="单据状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择单据状态">
          <el-option label="未分拣" value="0"></el-option>
          <el-option label="审核已分拣" value="1"></el-option>
          <el-option label="已发货" value="3"></el-option>
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['carbon:Grain:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['carbon:Grain:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['carbon:Grain:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="GrainList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="50" label="编号" />
      <el-table-column label="单据号" align="center" prop="orderId" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.status == '0'">
            未采购
          </el-tag>
          <el-tag effect="dark" type="info" v-else-if="scope.row.status == '1'">
            采购中
          </el-tag>
          <el-tag effect="dark" type="success" v-else>
            采购完成
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="createBy" />
      <el-table-column label="申请日期" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createStatus, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请状态" align="center" prop="createStatus">
        <template slot-scope="scope">
          <el-tag effect="dark"
            :type="scope.row.createStatus == '0' ? 'danger' : (scope.row.createStatus == '1' ? 'warning' : 'primary')">
            {{ scope.row.createStatus == '0' ? '待审核' : (scope.row.createStatus == '1' ? '已审核' : '未提交') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="updateBy" />
      <el-table-column label="审核日期" align="center" prop="updateTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="wareoutStatus">
        <template slot-scope="scope">

          <el-tag effect="dark" type="danger" v-if="scope.row.wareoutStatus == '2'">
            驳回
          </el-tag>
          <el-tag effect="dark" type="info" v-else-if="scope.row.wareoutStatus == '1'">
            审核通过
          </el-tag>
          <el-tag effect="dark" v-else>
            待审核
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['carbon:Grain:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-message-solid" v-if="scope.row.wareoutStatus == '0'"
            @click="handleWareOutStatus(scope.row)" v-hasPermi="['carbon:Grain:edit']">审核</el-button>
          <el-button
            v-if="scope.row.createStatus != '0' || (scope.row.createStatus == '1' && scope.row.updateStatus == '0')"
            size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改入库信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单据" v-if="form.id != null">
          <el-input v-model="form.orderId" placeholder="请输入单据id" :disabled="true" />
        </el-form-item>
        <el-form-item label="业务类型" prop="businessId">
          <el-select v-model="form.businessId" placeholder="请选择业务类型" :disabled="this.type == '123' || this.type == '6'">
            <el-option label="生产入库" :value="'0'"></el-option>
            <el-option label="采购入库" :value="'1'"></el-option>
            <el-option label="退货入库" :value="'2'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同类型" prop="contractId">
          <el-select v-model="form.contractId" placeholder="请选择合同类型" :disabled="this.type != '0' || this.type == '6'">
            <el-option label="采购合同" :value="'0'"></el-option>
            <el-option label="销售合同" :value="'1'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="providerId">
          <el-select v-model="form.providerId" placeholder="请选择供应商" :disabled="this.type == '123' || this.type == '6'">
            <el-option v-for="item in providerList" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="wareName">
          <el-cascader v-model="form.wareName" :options="wareList" :props="props" clearable
            :disabled="this.type == '123' || this.type == '6'"></el-cascader>
        </el-form-item>
        <el-form-item label="生产单位" prop="productName">
          <el-cascader v-model="form.productName" :options="productList" :props="props1" clearable
            :disabled="this.type == '123' || this.type == '6'"></el-cascader>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" :disabled="this.type == '123' || this.type == '6'" v-model="form.remark"
            placeholder="请输入备注" />
        </el-form-item>


        <el-divider content-position="center">商品信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddGoods">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteGoods">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="goodsList" :row-class-name="rowGoodsIndex" @selection-change="handleGoodsSelectionChange"
          ref="goods" :disabled="this.type == '6'">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column type="index" width="50" label="编号" align="center" />
          <el-table-column label="商品" prop="goodsName" width="180" align="center">
            <template slot-scope="scope">
              <el-cascader v-model="scope.row.goodsSelectName" :options="selectGoodsList" :props="props2" clearable
                ref="cascader" @change="handleGoodsName(scope.row)" :disabled="scope.row.id != null"></el-cascader>
            </template>
          </el-table-column>
          <el-table-column label="补货数量" prop="replenishmentNum" width="150" align="center">
            <template slot-scope="scope">
              <el-input-number size="small" v-model="scope.row.replenishmentNum" :min="0"
                :max="scope.row.goodsNum >= '' ? goodsNum : scope.row.goodsNum"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="商品价格" prop="goodsPrice" width="150" align="center">
            <template slot-scope="scope">
              <el-input-number size="small" v-model="scope.row.goodsPrice" :min="0"
                :max="scope.row.goodsPrice >= '' ? goodsNum : scope.row.goodsPrice" :disabled="true"></el-input-number>
            </template>
          </el-table-column>

          <el-table-column label="商品类型" prop="goodsType" width="150" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.goodsType" placeholder="请选择商品类型" :disabled="true">
                <el-option label="物料" value="0"></el-option>
                <el-option label="原料" value="1"></el-option>
              </el-select>
            </template>

          </el-table-column>
          <el-table-column label="商品图片" prop="goodsImg" width="150" align="center">
            <template slot-scope="scope">
              <el-image :src="scope.row.goodsImg" fit="cover" style="width:70px;height:70px;" :disabled="true">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="this.type != '6'">
        <el-button type="success" v-if="this.form.createStatus == null" @click="submitForm1">保 存</el-button>
        <el-button type="primary" v-if="this.form.createStatus == '2'" @click="submitForm">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-if="this.type == '6'">
        <el-button type="success" @click="submitForm2">通 过</el-button>
        <el-button type="primary" @click="submitForm3">驳 回</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updateRepairStatus, delStorageInfoGoods, changeCreateStatus, changeGrainStatus, listGrain, getGrain, delGrain, addGrain, updateGrain } from "@/api/wms/grain";
import { providerList } from "@/api/wms/provider"
import { getCascaderWare } from "@/api/wms/ware"
import { getProductTreeNode } from "@/api/wms/product"
import { selectGoodsInfoList, delGoods } from "@/api/wms/goods"
export default {
  name: "Grain",
  data () {
    return {
      goodsNum: 999999,
      props2: {
        children: 'children',
        label: 'goodsName',
        value: "id",
      },
      // 所有商品信息
      selectGoodsList: [],
      // 商品信息表格数据
      goodsList: [],
      // 情况 123
      type: '0',
      // 生产厂家
      productList: [],
      props1: {
        value: 'id',
        label: 'name',
        children: "children"
      },
      //仓库
      wareList: [],
      props: {
        value: 'id',
        label: 'wareName',
        children: "children"
      },
      // 供应商
      providerList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库信息表格数据
      GrainList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        flag: 3
      },
      // 表单参数
      form: {
        // 单据状态
        orderStatus: '0',
        // 入库状态
        status: '0',
        // 申请状态
        createStatus: '0',
        // 审核状态
        updateStatus: '0'
      },
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "单据不能为空", trigger: "blur" }
        ],
        businessId: [
          { required: true, message: "业务类型", trigger: "change" }
        ],
        contractId: [
          { required: true, message: "合同类型", trigger: "change" }
        ],
        providerId: [
          { required: true, message: "供应商不能为空", trigger: "change" }
        ],
        productName: [
          { required: true, message: "生产单位", trigger: "change" }
        ],
        wareName: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],

      }
    };
  },
  created () {
    this.getList();
    this.getproviderList();
    this.getProductTreeList()
    this.getWareList()
    this.getSelectGoodsList()
  },
  methods: {
    handleGoodsName (row) {
      var flag = false;
      var nodesInfo = this.$refs['cascader'].getCheckedNodes()
      console.log(nodesInfo);
      nodesInfo.forEach(element => {
        this.goodsList.forEach(item => {
          if (item.id == element.data.id) {
            flag = true;
            this.$message.error("该商品:" + element.data.goodsName + "已存在,请勿重复添加！")
            return;
          }
        })
        if (!flag) {
          row.goodsImg = element.data.goodsImg;
          row.goodsName = element.data.goodsName;
          row.replenishmentNum = element.data.replenishmentNum;
          row.goodsNum = element.data.goodsNum;
          row.remark = element.data.remark;
          row.id = element.data.id;
          row.goodsPrice = element.data.goodsPrice;
          row.goodsType = element.data.goodsType; s
        }
      });
      console.log(row);
    },
    // 获取商品信息 选择器
    getSelectGoodsList (storageId) {
      selectGoodsInfoList(storageId).then(res => {
        this.selectGoodsList = res.data
      })

    },
    // 获取生产单位树形结构
    getProductTreeList () {
      getProductTreeNode().then(res => {
        this.productList = res.data
      })
    },
    // 格式化数据，递归将空的children置为undefined
    formatData (data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.formatData(data[i].children)
        }
      }
      return data;
    },
    // 获取仓库信息
    getWareList () {
      getCascaderWare().then(res => {
        this.wareList = this.formatData(res.data)
      })
    },
    // 生成采购申请
    handleUpdateStatus (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认生成采购申请编号为"' + ids + '"的数据项？').then(function () {
        // return delGrain(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("生成采购申请成功");
      }).catch(() => {
      });
    },
    // 所有供应商信息
    getproviderList () {
      providerList().then(res => {
        this.providerList = res.data
      })
    },
    /** 查询入库信息列表 */
    getList () {
      this.loading = true;
      listGrain(this.queryParams).then(response => {
        this.GrainList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.goodsList = []
      this.type = "0"
      this.form = {
        createStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        flag: 3
      }
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.getProductTreeList()
      this.getWareList()
      this.reset();
      this.getSelectGoodsList(null)
      this.open = true;
      this.title = "添加出库信息";
    },
    /** 出库申请审核 */
    handleWareOutStatus (row) {
      this.reset();
      const id = row.id || this.ids
      this.getSelectGoodsList(id)
      this.type = '6'
      getGrain(id).then(response => {
        this.form = response.data;
        this.goodsList = response.data.goodsList;
        this.open = true;
        this.title = "审核出库信息";
      });
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const id = row.id || this.ids
      this.getSelectGoodsList(id)
      if (row.createStatus == '0' || (row.createStatus == '1' && row.updateStatus == '1' && row.status != '2')) {
        this.type = '123'
      } else if (row.createStatus != '0' || (row.createStatus == '1' && row.updateStatus == '0')) {
        this.type = '45'
      }
      getGrain(id).then(response => {
        this.form = response.data;
        this.goodsList = response.data.goodsList;
        this.open = true;
        this.title = "修改出库信息";
      });
    },
    /** 通过按钮 */
    submitForm2 () {
      this.form.repairStatus = '1';
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateRepairStatus(this.form.id, this.form.repairStatus).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.open = false;
            this.reset();
            this.getList();
          });
        }
      });
    },
    /** 驳回按钮 */
    submitForm3 () {
      this.form.repairStatus = '2';
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateRepairStatus(this.form.id, this.form.repairStatus).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.open = false;
            this.reset();
            this.getList();
          });
        }
      });
    },
    /** 保存按钮 */
    submitForm1 () {
      this.form.createStatus = '3';
      this.submitForm();
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.createStatus == '3') {
            this.form.createStatus = '2'
          } else {
            this.form.createStatus = '0'
          }
          if (this.form.id == null) {
            this.form.goodsList = this.goodsList;
          }
          addGrain(this.form).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.open = false;
            this.reset();
            console.log(this.form);
            this.getList();
          });
        }
      });
    },
    /** 商品信息序号 */
    rowGoodsIndex ({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 商品信息添加按钮操作 */
    handleAddGoods () {
      let obj = {};
      obj.goodsName = "";
      obj.goodsPrice = "";
      obj.goodsTotal = "";
      obj.goodsNum = "";
      obj.goodsType = "";
      obj.goodsStatus = "";
      obj.goodsImg = "";
      obj.remark = "";
      this.goodsList.push(obj);
    },
    /** 商品信息删除按钮操作 */
    handleDeleteGoods () {
      if (this.checkedGoods.length == 0) {
        this.$modal.msgError("请先选择要删除的商品信息数据");
      } else {
        var ids = "";
        this.checkedGoods.forEach(item => {
          if (this.goodsList[item - 1].id != null) {
            ids += this.goodsList[item - 1].id + ","
          }
        })
        if (ids != "") {
          delStorageInfoGoods(this.form.id, ids).then(res => {
            this.$message.success("删除成功");
          })
        }

        const goodsList = this.goodsList;
        const checkedGoods = this.checkedGoods;
        this.goodsList = goodsList.filter(function (item) {
          return checkedGoods.indexOf(item.index) == -1
        });
      }
    },
    /** 商品复选框选中数据 */
    handleGoodsSelectionChange (selection) {
      this.checkedGoods = selection.map(item => item.index)
    },

    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除入库信息编号为"' + ids + '"的数据项？').then(function () {
        return delGrain(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
  }
};
</script>
<style lang="scss" scoped>
.el-image {
  border-radius: 5px;
  background-color: #ebeef5;
  box-shadow: 0 0 5px 1px #ccc;

  ::v-deep .el-image__inner {
    transition: all 0.3s;
    cursor: pointer;

    &:hover {
      transform: scale(1.2);
    }
  }

  ::v-deep .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    color: #909399;
    font-size: 40px;
  }
}
</style>
